package com.thd.springboottest.sso.client.controller;

import com.thd.springboottest.sso.client.service.LoginService;
import com.thd.springboottest.sso.client.service.SessionIdUtil;
import com.thd.springboottest.sso.client.vo.Store;
import com.thd.springboottest.sso.vo.AuthBean;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * com.thd.springboottest.sso.client.controller.ClientController
 *
 * @author: wanglei62
 * @DATE: 2021/8/20 18:56
 **/
@RequestMapping("ssoclient")
@Controller
public class SsoClientController {

    @ResponseBody
    @RequestMapping("/loginCb")
    // url : http://127.0.0.1:8899/ssoclient/loginCb
    public ResponseEntity loginCb(@RequestParam(value="ssoToken",required = false) String ssoToken, HttpServletResponse response) throws IOException {
        if(null == ssoToken || ssoToken.length() == 0){
            throw new RuntimeException("ssoToken can not be null");
        }

        // 到SSOServer 验证 ssoToken 是否合法
        AuthBean auth = SessionIdUtil.checkSsoToken(ssoToken);
        if(null != auth){ // 验证成功

            // 执行本系统的登录
            String sessionId = LoginService.loginAndSetCookie(auth,response);
            AuthBean temp = Store.findBySessionId(sessionId);
            return ResponseEntity.ok(temp);
        }else{ // 验证失败
            return ResponseEntity.ok("用户不合法");
        }

    }

    @ResponseBody
    @RequestMapping("/testSessionIdUtil")
    // url : http://127.0.0.1:8898/ssoclient/testSessionIdUtil
    public ResponseEntity testSessionIdUtil(HttpServletRequest request){
        String sessionId = SessionIdUtil.getSessionId(request);
        return ResponseEntity.ok(sessionId);
    }


    @ResponseBody
    @RequestMapping("/info/info")
    // url : http://127.0.0.1:8898/ssoclient/info/info
    public ResponseEntity info(HttpServletRequest request){
        String sessionId = SessionIdUtil.getSessionId(request);
        AuthBean auth = Store.findBySessionId(sessionId);
        return ResponseEntity.ok(auth);
    }
}
